<template>
  <!-- 来电查询 -->
  <div class="app-page">
    <el-table-form ref="form" :model="query">
      <el-form-item class="merge-item">
        <el-select v-model="qtype" style="width: 170px; margin-right: 2px;">
          <el-option value="phone" label="来电号码" />
          <el-option value="csmCode" label="客户编号" />
          <el-option value="csmName" label="客户名称" />
        </el-select>
        <el-input v-model="txt" placeholder="请输入" clearable />
      </el-form-item>
      <el-form-item label="话务员:">
        <el-select v-model="query.callerId" filterable clearable placeholder="请选择">
          <el-option
            v-for="item in transactorList"
            :key="item.userId"
            :label="item.userName"
            :value="item.userId"
          />
        </el-select>
      </el-form-item>
      <el-form-item :table-form-merge="2" class="merge-item" label="去电时间:">
        <el-date-picker
          v-model="date"
          type="daterange"
          range-separator="至"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
        />
      </el-form-item>
      <template v-slot:btns>
        <el-button type="primary" icon="el-icon-search" @click="search">查询</el-button>
      </template>
    </el-table-form>
    <div style="margin-bottom: 10px;">
      <div>
        <el-button type="primary" icon="el-icon-download" @click="exportFile">导出</el-button>
      </div>
    </div>
    <lb-table
      ref="lbTable"
      v-loading="$loadingPlugin.fetchData"
      v-el-height-adaptive-table="{bottomOffset:10}"
      border
      highlight-current-row
      element-loading-text="加载中"
      :column="tableData.column"
      :data="tableData.data"
      pagination
      :total="tableData.total"
      custom-column
      :row-class-name="tableRowClassName"
      @fetch="fetchData"
    />
    <audio id="callRecordAudio">浏览器不支持</audio>
  </div>
</template>

<script>
  import { queryCallBackList, queryCallBackListExport } from '@/api'
  import { parseTime } from '@/utils'
  import moment from 'dayjs'
  import { mapGetters } from 'vuex'

  export default {
    name: 'callUp',
    props: {
      transactorList: {
        type: Array,
        required: true
      }
    },
    data() {
      return {
        callRecordAudio: undefined,
        callStatusMap: [],
        taskTypeMap: [],
        qtype: 'phone',
        txt: '',
        date: [moment().startOf('day'), moment().endOf('day')],
        query: {
          callerId: ''
        },
        tableData: {
          total: 0,
          column: [
            {
              type: 'index'
            },
            {
              prop: 'callCode',
              label: '来电编号',
              width: 160
            },
            {
              prop: 'phone',
              label: '去电号码',
              width: 130
            },
            {
              prop: 'callerName',
              label: '话务员'
            },
            {
              prop: 'csmCode',
              label: '客户编号'
            },
            {
              prop: 'csmName',
              label: '客户名称'
            },
            {
              prop: 'csmAddress',
              label: '客户地址',
              width: 180
            },
            {
              prop: 'startDt',
              label: '去电时间',
              width: 160,
              render: (h, { row }) => <span>{ row.startDt && parseTime(row.startDt, '{y}-{m}-{d} {h}:{i}:{s}') }</span>
            },
            {
              prop: 'endDt',
              label: '挂机时间',
              width: 160,
              render: (h, { row }) => <span>{ row.endDt && parseTime(row.endDt, '{y}-{m}-{d} {h}:{i}:{s}') }</span>
            },
            {
              prop: 'timeSpan',
              align: 'right',
              label: '去电时长(秒)',
              width: 130
            },
            {
              label: '语音',
              prop: 'fileUrl',
              fixed: 'right',
              width: 65,
              render: (h, scope) => {
                return (
                  <div>
                    {scope.row.fileUrl && scope.row.paused && <i class='colBtn el-icon-video-play'
                                                                 onClick={() => this.play(scope, scope.row.callId)}
                    ></i>}&nbsp;
                    {scope.row.fileUrl && !scope.row.paused && <i class='colBtn el-icon-video-pause'
                                                                  onClick={() => this.play(scope, scope.row.callId)}
                    ></i>}&nbsp;
                    {scope.row.fileUrl &&
                    <i class='colBtn el-icon-download' onClick={() => this.download(scope.row)}></i>}
                  </div>
                )
              }
            }
          ],
          data: []
        }
      }
    },
    computed: {
      ...mapGetters([
        'exportDomain', 'corpSettingData'
      ])
    },
    mounted() {
      this.callRecordAudio = document.getElementById('callRecordAudio')
    },
    methods: {
      _getQuery(obj) {
        const query = {}
        for (const key in obj) {
          if (obj.hasOwnProperty(key)) {
            if (obj[key] !== '') {
              query[key] = obj[key]
            }
          }
        }
        return query
      },
      async fetchData({ currentPage, pageSize }) {
        const query = {
          ...this._getQuery(this.query),
          currentPage,
          pageSize
        }
        if (this.date && this.date.length > 0) {
          query.startDt = moment(this.date[0]).format()
          query.startDtEnd = moment(this.date[1]).format()
        }
        const diff = moment(this.date[1]).diff(moment(this.date[0]), 'days')
        if (diff > 93) {
          this.$message.warning('选择来电时间相差不能超过3个月')
          return
        }
        const res = await queryCallBackList(query)
        this.tableData.data = res.data.rows.map(item => {
          return {
            ...item,
            paused: true
          }
        })
        if (currentPage === 1) this.tableData.total = res.data.total
      },
      search() {
        this.$refs.lbTable.fetch({ currentPage: 1 })
      },
      exportFile() {
        const _this = this
        this.$confirm(`确定导出数据？`, '提示', {
          type: 'info'
        }).then(() => {
          const copyColumn = JSON.parse(JSON.stringify(this.tableData.column))
          copyColumn.pop()
          const str = {}
          copyColumn.forEach(item => {
            str[item.prop] = item.label
          })
          queryCallBackListExport({
            paramInfo: _this._getQuery(_this.query),
            kv: str // 表格列
          }).then((res) => {
            window.open(`${this.exportDomain}/page/export/frame?key=${res.data}`, '_blank')
          })
        })
      },
      play(scope, id) {
        if (this.callRecordAudio.dataset.id === id) {
          if (this.callRecordAudio.paused) {
            this.callRecordAudio.play()
            scope.row.paused = false
            this.callRecordAudio.addEventListener('ended', function() {
              scope.row.paused = true
            }, false)
          } else {
            this.callRecordAudio.pause()
          }
        } else {
          this.callRecordAudio.dataset.id = id
          this.callRecordAudio.pause()
          this.callRecordAudio.src = `http://${this.corpSettingData.pbxURL}/download/audio?path=${scope.row.fileUrl}`
          this.callRecordAudio.play()
          scope.row.paused = false
          this.callRecordAudio.addEventListener('ended', function() {
            scope.row.paused = true
          }, false)
        }
      },
      download(row) {
        const path = `http://${this.corpSettingData.pbxURL}/download/audio?path=${row.fileUrl}`
        window.open(path)
      },
      // 设置颜色
      tableRowClassName({ row }) {
        if (row.callStatus === 2) {
          return 'success-row'
        } else if (row.callStatus === 3) {
          return 'warning-row'
        }
        return ''
      }
    }
  }
</script>

<style lang="scss" scoped>
.app-page {
  /deep/ .colBtn.el-icon-video-play,
  /deep/ .colBtn.el-icon-video-pause,
  /deep/ .colBtn.el-icon-download {
    font-size: 20px;
    color: #01999F;
    cursor: pointer;
  }
}
/deep/ .el-table tr.warning-row {
  background: #F99;
}
.el-table .success-row {
  background-color: #f0f9eb;
}
</style>
